import functools

from flask import url_for, session, redirect

from .config import OAUTH2_OPEN


def need_login(f):
    @functools.wraps(f)
    def decorate(*p1, **p2):
        if 'gitlab_token' in session or not OAUTH2_OPEN:
            return f(*p1, **p2)
        else:
            return redirect(url_for('login'))

    return decorate


def progress(name):
    def inner(f):
        @functools.wraps(f)
        def decorate(*args, **kwargs):
            import threading
            from core.documents import TaskProgress

            def running(tkp):
                for i in f(*args, **kwargs):
                    tkp.rate = i
                tkp.finish()

            key = f.__name__ + str(args) + str(kwargs)
            task = TaskProgress.objects(key=key).first()
            if task:
                if task.rate >= 100:
                    task.rate = 0
                    task.save()
                else:
                    return key
            else:
                task = TaskProgress(key=key, name=name,count=100,index=0)
            t = threading.Thread(target=running, args=(task,))
            t.start()
            return key

        return decorate

    return inner
